import {
    CallHandler,
    ExecutionContext,
    Injectable,
    NestInterceptor,
} from '@nestjs/common';

import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';

export interface Response<T> {
    code: number;
    success: boolean;
    message: string;
    data: T;
};

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, Response<T>> {
    intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
        return next.handle().pipe(
            map(data => ({
                code: context.switchToHttp().getResponse().statusCode || 200,
                success: true,
                message: data?.message || '请求成功',
                data: data?.data !== undefined ? data.data : data, // 兼容已有结构
            }))
        );
    }
}